<template>
  <view class="drag-combine-page">
    <!-- 页面头部 -->
    <view class="page-header">
      <text class="page-title">拖拽信任组合</text>
      <text class="page-subtitle">拖拽卡牌进行组合，创造新的信任效果</text>
    </view>
    
    <!-- 操作工具栏 -->
    <view class="toolbar">
      <button class="tool-btn" @click="showHelp">
        <text class="btn-icon">❓</text>
        <text class="btn-text">帮助</text>
      </button>
      
      <button class="tool-btn" @click="showStatistics">
        <text class="btn-icon">📊</text>
        <text class="btn-text">统计</text>
      </button>
      
      <button class="tool-btn" @click="clearAll">
        <text class="btn-icon">🗑️</text>
        <text class="btn-text">清空</text>
      </button>
      
      <button class="tool-btn" @click="addRandomCard">
        <text class="btn-icon">➕</text>
        <text class="btn-text">添加卡牌</text>
      </button>
    </view>
    
    <!-- 卡牌区域 -->
    <view class="cards-area">
      <!-- 可拖拽卡牌列表 -->
      <view class="draggable-cards">
        <text class="section-title">可拖拽卡牌</text>
        <view class="cards-grid">
          <TrustDragCard 
            v-for="card in draggableCards" 
            :key="card.id"
            :card="card"
            :draggable="true"
            @drag-start="handleDragStart"
            @drag-end="handleDragEnd"
            @combination-success="handleCombinationSuccess"
            @combination-failed="handleCombinationFailed"
          />
        </view>
      </view>
      
      <!-- 组合区域 -->
      <view class="combination-area">
        <text class="section-title">组合区域</text>
        <view class="combination-zones">
          <view 
            class="combination-zone" 
            v-for="(zone, index) in combinationZones" 
            :key="zone.id"
            :class="{ 'zone-active': zone.isActive }"
          >
            <text class="zone-label">组合区域 {{ index + 1 }}</text>
            <view class="zone-content">
              <TrustDragCard 
                v-if="zone.card1"
                :card="zone.card1"
                :draggable="false"
                :isDropTarget="true"
                @drop="handleZoneDrop(zone.id, $event)"
              />
              <view v-else class="empty-zone">
                <text class="empty-text">拖拽卡牌到这里</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 组合结果 -->
    <view class="combination-results" v-if="combinationResults.length > 0">
      <text class="section-title">组合结果</text>
      <view class="results-list">
        <view 
          class="result-item" 
          v-for="result in combinationResults" 
          :key="result.id"
          :class="result.type"
        >
          <view class="result-header">
            <text class="result-icon">{{ result.icon }}</text>
            <text class="result-title">{{ result.title }}</text>
            <text class="result-time">{{ formatTime(result.timestamp) }}</text>
          </view>
          <text class="result-description">{{ result.description }}</text>
          <view class="result-effects" v-if="result.effects">
            <view 
              class="effect-item" 
              v-for="effect in result.effects" 
              :key="effect.id"
            >
              <text class="effect-icon">{{ effect.icon }}</text>
              <text class="effect-text">{{ effect.description }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 帮助模态框 -->
    <view v-if="showHelpModal" class="help-modal">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">拖拽组合帮助</text>
          <button class="close-btn" @click="closeHelp">×</button>
        </view>
        
        <view class="help-content">
          <view class="help-section">
            <text class="help-title">如何拖拽组合</text>
            <text class="help-text">1. 从左侧卡牌列表拖拽卡牌到组合区域</text>
            <text class="help-text">2. 将两张卡牌拖拽到同一个组合区域</text>
            <text class="help-text">3. 系统会自动计算组合效果</text>
          </view>
          
          <view class="help-section">
            <text class="help-title">组合规则</text>
            <text class="help-text">• 信任值组合：两张卡牌信任值相加</text>
            <text class="help-text">• 属性协同：相同属性卡牌产生协同效果</text>
            <text class="help-text">• 完美匹配：高信任值卡牌完美组合</text>
            <text class="help-text">• 互补组合：不同属性卡牌互补组合</text>
          </view>
          
          <view class="help-section">
            <text class="help-title">操作提示</text>
            <text class="help-text">• 长按卡牌开始拖拽</text>
            <text class="help-text">• 拖拽到目标区域释放</text>
            <text class="help-text">• 查看组合预览效果</text>
            <text class="help-text">• 确认组合结果</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 统计模态框 -->
    <view v-if="showStatsModal" class="stats-modal">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">组合统计</text>
          <button class="close-btn" @click="closeStats">×</button>
        </view>
        
        <view class="stats-content">
          <view class="stat-section">
            <text class="stat-title">拖拽统计</text>
            <view class="stat-item">
              <text class="stat-label">总拖拽次数</text>
              <text class="stat-value">{{ statistics.totalDrags }}</text>
            </view>
            <view class="stat-item">
              <text class="stat-label">成功拖拽</text>
              <text class="stat-value">{{ statistics.successfulDrags }}</text>
            </view>
            <view class="stat-item">
              <text class="stat-label">成功率</text>
              <text class="stat-value">{{ statistics.successRate.toFixed(1) }}%</text>
            </view>
            <view class="stat-item">
              <text class="stat-label">平均时长</text>
              <text class="stat-value">{{ formatDuration(statistics.averageDuration) }}</text>
            </view>
          </view>
          
          <view class="stat-section">
            <text class="stat-title">组合统计</text>
            <view class="stat-item">
              <text class="stat-label">总组合次数</text>
              <text class="stat-value">{{ statistics.totalCombinations }}</text>
            </view>
            <view class="stat-item">
              <text class="stat-label">成功组合</text>
              <text class="stat-value">{{ statistics.successfulCombinations }}</text>
            </view>
            <view class="stat-item">
              <text class="stat-label">组合成功率</text>
              <text class="stat-value">{{ statistics.combinationSuccessRate.toFixed(1) }}%</text>
            </view>
          </view>
          
          <view class="stat-section">
            <text class="stat-title">最常用组合</text>
            <view class="popular-combinations">
              <view 
                class="combination-item" 
                v-for="combo in popularCombinations" 
                :key="combo.card1Id + '-' + combo.card2Id"
              >
                <text class="combo-text">{{ combo.card1Id }} + {{ combo.card2Id }}</text>
                <text class="combo-count">{{ combo.count }} 次</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import TrustDragCard from '@/pages/game/trust-fall/components/trust/TrustDragCard.vue'
import trustDragManager from '@/utils/trust-drag-manager.js'
import trustCardManager from '@/utils/trust-card-manager.js'

export default {
  name: 'DragCombinePage',
  components: {
    TrustDragCard
  },
  
  data() {
    return {
      draggableCards: [],
      combinationZones: [
        { id: 'zone1', card1: null, card2: null, isActive: false },
        { id: 'zone2', card1: null, card2: null, isActive: false },
        { id: 'zone3', card1: null, card2: null, isActive: false }
      ],
      combinationResults: [],
      showHelpModal: false,
      showStatsModal: false,
      statistics: {},
      popularCombinations: []
    }
  },
  
  onLoad() {
    this.initializePage()
  },
  
  methods: {
    // 初始化页面
    initializePage() {
      this.loadDraggableCards()
      this.loadCombinationHistory()
      this.updateStatistics()
    },
    
    // 加载可拖拽卡牌
    loadDraggableCards() {
      const cards = trustCardManager.getAllCards()
      if (cards.length === 0) {
        // 创建一些默认卡牌
        this.createDefaultCards()
      } else {
        this.draggableCards = cards
      }
    },
    
    // 创建默认卡牌
    createDefaultCards() {
      const defaultCards = [
        {
          id: 'card1',
          name: '信任卡牌',
          description: '一张基础的信任卡牌',
          trustValue: 60,
          attributes: {
            '合作': 10,
            '诚信': 8
          },
          badges: [
            { id: 'basic', icon: '⭐', type: 'achievement' }
          ]
        },
        {
          id: 'card2',
          name: '合作卡牌',
          description: '专注于合作的卡牌',
          trustValue: 70,
          attributes: {
            '合作': 15,
            '沟通': 12
          },
          badges: [
            { id: 'cooperation', icon: '🤝', type: 'special' }
          ]
        },
        {
          id: 'card3',
          name: '诚信卡牌',
          description: '强调诚信的卡牌',
          trustValue: 80,
          attributes: {
            '诚信': 20,
            '可靠': 15
          },
          badges: [
            { id: 'integrity', icon: '💎', type: 'vip' }
          ]
        }
      ]
      
      defaultCards.forEach(card => {
        trustCardManager.addCard(card)
      })
      
      this.draggableCards = defaultCards
    },
    
    // 加载组合历史
    loadCombinationHistory() {
      trustDragManager.loadCombinationHistory()
      this.combinationResults = trustDragManager.getCombinationHistory(10)
    },
    
    // 更新统计信息
    updateStatistics() {
      this.statistics = trustDragManager.getDragStatistics()
      this.popularCombinations = trustDragManager.getMostUsedCombinations(5)
    },
    
    // 处理拖拽开始
    handleDragStart(event) {
      console.log('Drag started:', event)
    },
    
    // 处理拖拽结束
    handleDragEnd(event) {
      console.log('Drag ended:', event)
    },
    
    // 处理组合成功
    handleCombinationSuccess(event) {
      const result = {
        id: Date.now(),
        type: 'success',
        icon: '✅',
        title: '组合成功',
        description: event.effects.map(e => e.description).join(', '),
        effects: event.effects,
        timestamp: Date.now()
      }
      
      this.combinationResults.unshift(result)
      
      // 限制结果数量
      if (this.combinationResults.length > 20) {
        this.combinationResults = this.combinationResults.slice(0, 20)
      }
      
      uni.showToast({
        title: '组合成功！',
        icon: 'success'
      })
    },
    
    // 处理组合失败
    handleCombinationFailed(event) {
      const result = {
        id: Date.now(),
        type: 'failed',
        icon: '❌',
        title: '组合失败',
        description: event.reason,
        timestamp: Date.now()
      }
      
      this.combinationResults.unshift(result)
      
      uni.showToast({
        title: '组合失败',
        icon: 'error'
      })
    },
    
    // 处理区域放置
    handleZoneDrop(zoneId, event) {
      const zone = this.combinationZones.find(z => z.id === zoneId)
      if (zone) {
        if (!zone.card1) {
          zone.card1 = event.card
        } else if (!zone.card2) {
          zone.card2 = event.card
          // 尝试组合
          this.attemptCombination(zone)
        }
      }
    },
    
    // 尝试组合
    attemptCombination(zone) {
      if (zone.card1 && zone.card2) {
        const effects = trustDragManager.calculateCombinationEffects(zone.card1, zone.card2)
        
        if (effects.length > 0) {
          // 组合成功
          this.handleCombinationSuccess({
            card1: zone.card1,
            card2: zone.card2,
            effects: effects
          })
          
          // 清空区域
          zone.card1 = null
          zone.card2 = null
        } else {
          // 组合失败
          this.handleCombinationFailed({
            card1: zone.card1,
            card2: zone.card2,
            reason: '无法组合'
          })
        }
      }
    },
    
    // 显示帮助
    showHelp() {
      this.showHelpModal = true
    },
    
    // 关闭帮助
    closeHelp() {
      this.showHelpModal = false
    },
    
    // 显示统计
    showStatistics() {
      this.updateStatistics()
      this.showStatsModal = true
    },
    
    // 关闭统计
    closeStats() {
      this.showStatsModal = false
    },
    
    // 清空所有
    clearAll() {
      uni.showModal({
        title: '确认清空',
        content: '确定要清空所有数据吗？',
        success: (res) => {
          if (res.confirm) {
            trustDragManager.clearAllData()
            this.combinationResults = []
            this.combinationZones.forEach(zone => {
              zone.card1 = null
              zone.card2 = null
            })
            this.updateStatistics()
            
            uni.showToast({
              title: '已清空',
              icon: 'success'
            })
          }
        }
      })
    },
    
    // 添加随机卡牌
    addRandomCard() {
      const randomCard = this.generateRandomCard()
      trustCardManager.addCard(randomCard)
      this.draggableCards.push(randomCard)
      
      uni.showToast({
        title: '添加成功',
        icon: 'success'
      })
    },
    
    // 生成随机卡牌
    generateRandomCard() {
      const names = ['信任卡', '合作卡', '诚信卡', '可靠卡', '真诚卡']
      const descriptions = ['一张随机生成的卡牌', '具有特殊属性的卡牌', '值得信赖的卡牌']
      const attributes = ['合作', '诚信', '沟通', '可靠', '真诚']
      
      const name = names[Math.floor(Math.random() * names.length)]
      const description = descriptions[Math.floor(Math.random() * descriptions.length)]
      const trustValue = Math.floor(Math.random() * 100)
      
      const cardAttributes = {}
      const attributeCount = Math.floor(Math.random() * 3) + 1
      for (let i = 0; i < attributeCount; i++) {
        const attr = attributes[Math.floor(Math.random() * attributes.length)]
        cardAttributes[attr] = Math.floor(Math.random() * 20) + 1
      }
      
      return {
        id: `random_${Date.now()}`,
        name: name,
        description: description,
        trustValue: trustValue,
        attributes: cardAttributes,
        badges: []
      }
    },
    
    // 格式化时间
    formatTime(timestamp) {
      const date = new Date(timestamp)
      return date.toLocaleString()
    },
    
    // 格式化时长
    formatDuration(duration) {
      if (duration < 1000) {
        return `${Math.round(duration)}ms`
      } else {
        return `${(duration / 1000).toFixed(1)}s`
      }
    }
  }
}
</script>

<style scoped>
.drag-combine-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20rpx;
  color: white;
}

/* 页面头部 */
.page-header {
  text-align: center;
  margin-bottom: 30rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 20rpx;
  padding: 30rpx;
  backdrop-filter: blur(10rpx);
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 8rpx;
  text-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.2);
}

.page-subtitle {
  font-size: 24rpx;
  opacity: 0.8;
}

/* 工具栏 */
.toolbar {
  display: flex;
  gap: 16rpx;
  margin-bottom: 30rpx;
  flex-wrap: wrap;
}

.tool-btn {
  flex: 1;
  min-width: 120rpx;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: none;
  border-radius: 12rpx;
  padding: 16rpx 12rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
  cursor: pointer;
  transition: all 0.3s ease;
}

.tool-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: translateY(-2rpx);
}

.btn-icon {
  font-size: 24rpx;
}

.btn-text {
  font-size: 18rpx;
  font-weight: bold;
}

/* 卡牌区域 */
.cards-area {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

.draggable-cards,
.combination-area {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 24rpx;
  box-shadow: 0 8rpx 25rpx rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 20rpx;
  text-align: center;
}

.cards-grid {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.combination-zones {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.combination-zone {
  border: 2rpx dashed #e0e0e0;
  border-radius: 12rpx;
  padding: 20rpx;
  min-height: 200rpx;
  transition: all 0.3s ease;
}

.combination-zone.zone-active {
  border-color: #4caf50;
  background: rgba(76, 175, 80, 0.1);
}

.zone-label {
  font-size: 20rpx;
  color: #666;
  display: block;
  margin-bottom: 12rpx;
}

.zone-content {
  min-height: 150rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-zone {
  text-align: center;
  color: #999;
}

.empty-text {
  font-size: 24rpx;
}

/* 组合结果 */
.combination-results {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 24rpx;
  margin-top: 30rpx;
  box-shadow: 0 8rpx 25rpx rgba(0, 0, 0, 0.1);
}

.results-list {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.result-item {
  padding: 16rpx;
  border-radius: 12rpx;
  border-left: 4rpx solid #e0e0e0;
}

.result-item.success {
  background: rgba(76, 175, 80, 0.1);
  border-left-color: #4caf50;
}

.result-item.failed {
  background: rgba(244, 67, 54, 0.1);
  border-left-color: #f44336;
}

.result-header {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin-bottom: 8rpx;
}

.result-icon {
  font-size: 20rpx;
}

.result-title {
  font-size: 22rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
}

.result-time {
  font-size: 16rpx;
  color: #999;
}

.result-description {
  font-size: 18rpx;
  color: #666;
  margin-bottom: 8rpx;
  display: block;
}

.result-effects {
  display: flex;
  flex-direction: column;
  gap: 4rpx;
}

.effect-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
  font-size: 16rpx;
  color: #555;
}

.effect-icon {
  font-size: 14rpx;
}

.effect-text {
  font-size: 14rpx;
}

/* 模态框 */
.help-modal,
.stats-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
  max-width: 600rpx;
  max-height: 80vh;
  overflow-y: auto;
  color: #333;
  margin: 20rpx;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
  border-bottom: 1rpx solid #e0e0e0;
  padding-bottom: 16rpx;
}

.modal-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background: #f5f5f5;
  color: #666;
  font-size: 24rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

/* 帮助内容 */
.help-content {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.help-section {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.help-title {
  font-size: 22rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
}

.help-text {
  font-size: 18rpx;
  color: #666;
  line-height: 1.4;
}

/* 统计内容 */
.stats-content {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.stat-section {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.stat-title {
  font-size: 22rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8rpx 12rpx;
  background: #f8f9fa;
  border-radius: 8rpx;
}

.stat-label {
  font-size: 18rpx;
  color: #666;
}

.stat-value {
  font-size: 18rpx;
  font-weight: bold;
  color: #333;
}

.popular-combinations {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.combination-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8rpx 12rpx;
  background: #f8f9fa;
  border-radius: 8rpx;
}

.combo-text {
  font-size: 18rpx;
  color: #333;
}

.combo-count {
  font-size: 16rpx;
  color: #666;
}

/* 响应式设计 */
@media (max-width: 768rpx) {
  .drag-combine-page {
    padding: 16rpx;
  }
  
  .toolbar {
    flex-direction: column;
  }
  
  .tool-btn {
    flex-direction: row;
    justify-content: center;
  }
  
  .modal-content {
    margin: 16rpx;
    max-width: calc(100% - 32rpx);
  }
}
</style>

